<template>
  <GroupPage
    :search-form-props="{
      keywordSearchData: [{ key: 'teamName', label: '班组名称' }],
      title: '班组管理',
    }"
    group-size="small"
    group-title="班组信息"
    content-title="收费员列表"
    @search="onSearch"
  >
    <template #extraButtons>
      <a-button @click="handleAddTeam">
        <template #icon>
          <PlusOutlined />
        </template>
        新增班组
      </a-button>
      <a-button class="mx-4.5" type="primary" @click="showUpdateModal">
        <template #icon>
          <EditOutlined />
        </template>
        编辑班组
      </a-button>
      <a-button danger type="primary" class="mr-4.5" @click="handleDelTeam">
        <template #icon>
          <DeleteOutlined />
        </template>
        删除班组
      </a-button>
    </template>
    <template #group>
      <SpinSkeleton v-show="tableLoading || tableData.length > 0" :loading="tableLoading">
        <div
          v-for="(el, i) in tableData"
          :key="el.id"
          class="py-2 px-4 mb-2 cursor-pointer hover-container"
          :class="[curIndex === i ? 'bg-opacity-10 bg-color-active' : 'bg-header']"
          @click="selectTeam(i)"
        >
          <div :class="[curIndex === i ? 'text-color-active' : 'text-color-main']">
            {{ el.teamName }}
          </div>
        </div>
      </SpinSkeleton>
      <SlEmpty v-show="!tableLoading && tableData.length === 0" :description="emptyText"></SlEmpty>
    </template>
    <template #content>
      <SearchForm
        v-model:keyword="userKeyword"
        class="mb-0 mx-7 mt-6"
        :columns="userColumns"
        :keyword-search-data="[{ key: 'tollCollector', label: '收费员名称' }]"
        @search="onSearchUser"
      >
        <template #extraButtons>
          <a-button type="primary" :disabled="curIndex === -1 || tableLoading" @click="showUserSelectModal">
            <template #icon>
              <PlusOutlined />
            </template>
            新增收费员
          </a-button>
        </template>
      </SearchForm>
      <div class="flex-1 overflow-hidden">
        <SlTable
          class="mx-7"
          :columns="userColumns"
          row-key="id"
          :data-source="userTableData"
          :loading="userTableLoading"
          :search-model="userSearchModel"
          :ignore-keys="['teamId']"
        >
          <template #bodyCell="{ column, record }: BodyCellOptions<TollCollectorItem>">
            <div v-if="column.key === 'oper'">
              <a class="text-red-400" @click="handleRemoveUser(record)">移除</a>
            </div>
          </template>
        </SlTable>
      </div>
    </template>
    <CURDDialog
      create-title="新增班组"
      update-title="编辑班组"
      :show-options="showOptions"
      :model="teamModel"
      :model-form-setting="modelFormSetting"
      :table-data="tableData"
      :curd="curd"
      id-key="id"
      :reload-table="reloadTable"
    />
    <CURDDialog
      :show-options="showUserOptions"
      delete-message="确认移除该收费员吗？"
      :model="{}"
      :table-data="userTableData"
      :curd="usercurd"
      id-key="id"
      :reload-table="reloadUserTable"
    />
    <a-modal v-model:visible="userSelectModalVisible" title="添加收费员" :width="800" @ok="addUserToTeam">
      <UserSelect ref="userSelectIns" v-model:value="selectedUserIds" :disabled-value="cannotSelectUserIds" />
    </a-modal>
  </GroupPage>
</template>
<script lang="ts" setup>
import { message } from "ant-design-vue";
import { computed, onMounted, ref, watch } from "vue";
import { useI18n } from "/@/locales/useI18n";

import { TeamItem } from "/@/api/main/teamManage/models";
import { Api, addCollectorsToTeam } from "/@/api/main/teamManage";
import { useCURD } from "/@/hooks/useCURD";
import { RequestMethodEnum } from "/@/api/req/httpEnum";
import { CURDAction, FormItemComponentType, FormItemData, ShowCURDModalOptions } from "/@/components/CURDDialog/models";

import { useEmptyText } from "/@/hooks/useEmptyText";
import { PatternKey } from "/@/utils/verify";
import { PlusOutlined, EditOutlined, DeleteOutlined } from "@ant-design/icons-vue";
import type { TollCollectorItem } from "/@/api/main/civilizedService/models";
import { SelectExpose } from "/@/types/components";
import type { BodyCellOptions } from "/@/types/antd";
const { t } = useI18n();
/**
 * 班组
 */
const showOptions = ref<ShowCURDModalOptions>();
function handleAddTeam() {
  showOptions.value = { action: CURDAction.CREATE };
}
//编辑班组
function showUpdateModal() {
  let record = tableData.value[curIndex.value];
  showOptions.value = { action: CURDAction.UPDATE, record };
}
//删除班组
function handleDelTeam() {
  const record = tableData.value[curIndex.value];
  showOptions.value = {
    action: CURDAction.DELETE,
    record,
    message: "确认删除该班组吗？",
  };
}
//查询班组
async function onSearch(model) {
  await reloadTable({ model });
  reloadUserByIndex(0);
}
const teamModel = ref<TeamItem>({
  teamName: "",
  start: "",
  end: "",
});
//班组model Form
const modelFormSetting: FormItemData[] = [
  {
    key: "teamName",
    label: "班组名称",
    pattern: PatternKey.name,
    max: 32,
    required: true,
  },
  {
    key: "start",
    label: "上班时间",
    type: FormItemComponentType.TIMEPICKER,
    required: true,
  },
  {
    key: "end",
    label: "下班时间",
    type: FormItemComponentType.TIMEPICKER,
    required: true,
  },
];
//班组CRUD数据定义
const { tableData, tableLoading, reloadTable, curd, searchModel } = useCURD<TeamItem>({
  getPageUrl: Api.teamsPage,
  updateUrl: Api.teamsPage,
  deleteUrl: Api.teamsPage,
  createUrl: Api.teamsPage,
  pageSize: 999,
  loadOnMounted: false,
});

const { emptyText, modelForEmptyText } = useEmptyText();
watch(
  searchModel,
  (v) => {
    modelForEmptyText.value = v;
  },
  { deep: true }
);
//当前所选班组索引
const curIndex = ref(-1);
function selectTeam(i) {
  curIndex.value = i;
  //清空收费员搜索框
  userKeyword.value = "";
}
/**
 * 入口
 */
watch(curIndex, reloadUserByIndex);
onMounted(async () => {
  //加载班组
  await reloadTable();
  curIndex.value = 0;
});
/**
 * 收费员
 */
const userKeyword = ref("");
const showUserOptions = ref<ShowCURDModalOptions>();
const {
  tableData: userTableData,
  tableLoading: userTableLoading,
  reloadTable: reloadUserTable,
  curd: usercurd,
  searchModel: userSearchModel,
} = useCURD<TollCollectorItem>({
  getPageUrl: Api.teamCollectorsPage,
  pageSize: 999,
  deleteUrl: Api.teamCollectorsPage,
  loadOnMounted: false,
});
function reloadUserByIndex(v) {
  showUserOptions.value = void 0;
  const item = tableData.value[v];
  if (!item) {
    userTableData.value = [];
  } else {
    //加载角色用户列表
    reloadUserTable({
      model: { teamId: item.id },
    });
  }
}

// 搜索用户组的同时刷新用户table
watch(tableData, async () => {
  const item = tableData.value[0];
  if (!item) return;
  if (curIndex.value === 0) {
    reloadUserByIndex(0);
  } else {
    curIndex.value = 0;
  }
});
// 查询用户数据
function onSearchUser(model) {
  reloadUserTable({
    model,
  });
}
// 用户col
const userColumns = ref([
  {
    title: "收费员名称",
    dataIndex: "tollCollector",
  },
  {
    title: "备注",
    dataIndex: "remark",
  },
  {
    title: t("common.oper"),
    key: "oper",
  },
]);
//增加用户
const userSelectIns = ref<SelectExpose<TollCollectorItem>>();
const userSelectModalVisible = ref(false);
watch(userSelectModalVisible, (v) => {
  if (!v && userSelectIns.value) {
    userSelectIns.value.reset();
  }
});
const selectedUserIds = ref<number[]>([]);
const cannotSelectUserIds = ref<number[]>([]);
async function addUserToTeam() {
  if (selectedUserIds.value.length === 0) {
    return message.info("请至少选择一个收费员");
  }
  const team = tableData.value[curIndex.value];
  if (team) {
    const re = await addCollectorsToTeam({ teamId: team.id as number, tollCollectorIds: selectedUserIds.value });
    if (re !== null) {
      message.success("新增成功");
      reloadUserByIndex(curIndex.value);
      userSelectModalVisible.value = false;
    }
  }
}
function showUserSelectModal() {
  cannotSelectUserIds.value = userTableData.value.map((el) => el.tollCollectorId as number);
  userSelectModalVisible.value = true;
}
// 移除用户
function handleRemoveUser(record: TollCollectorItem) {
  showUserOptions.value = { action: CURDAction.DELETE, record };
}
</script>
